<template>
  <div style="margin-right: 10px">
    <el-card style="margin-bottom: 16px">
      <div slot="header">
        {{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}品类销售目标达成情况(单位：万){{ " " + dataYear.dataYear }}
        <!-- <span
                      ><i class="el-icon-collection"></i>
                      {{ query.salesGrade? query.salesGrade: query.proBrandList + " " }}年度完成率</span
                    > -->
      </div>
      <el-row :gutter="20">
        <el-col :span="16" :xs="24">
          <!-- <barLine :echartDataSku="barLineChart" /> -->
          <!-- 柱状图+折线图  :colors="color"-->
          <ve-histogram :data="barLineChart" :y-axis="yAxis" :extend="chartExtend" :settings="chartSettingscompleteRate"
            style="width: 100%; height: 100%"></ve-histogram>
        </el-col>
        <el-col :span="8" :xs="24">
          <el-table :data="barLineDatatarget" style="width: 100%" border :height="350"
            :row-class-name="tableRowClassName">
            <el-table-column prop="category" label="类别" width="125"></el-table-column>
            <el-table-column prop="salesAmount" label="实际销售额" width="150" :formatter="stateFormat">
            </el-table-column>
            <el-table-column :formatter="stateFormat" prop="targetAmount" label="销售目标" width="150"></el-table-column>
            <el-table-column :formatter="PerseFormat" prop="completeRate" label="达成率" width="100">
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <div slot="header" style="display: flex; justify-content: space-between">
        <!-- 销售目完成情况 -->
        <span><i class="el-icon-collection"></i>
          {{ query.salesGrade ? query.salesGrade : query.proBrandList + " " }}销售目完成情况(单位：万)</span>
        <span>
          类目：
          <el-select v-model="productView" placeholder="品类" @change="changeView"
            style="width: 100px; height: 30px; margin-left: 5px">
            <el-option v-for="dict in productViewList" :key="dict.value" :label="dict.label" :value="dict.label" />
          </el-select>
        </span>
      </div>
      <!-- <LineChart /> -->
      <!-- <div
        style="margin-left: 2px; margin-right: 2px; height: 410px"
        ref="salesQuantity"
      ></div> -->
      <ve-histogram :data="barLineData" :y-axis="yAxis" :extend="chartExtendcomplete" :settings="chartSettingscomplete"
        style="width: 100%; height: 100%"></ve-histogram>

      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column fixed prop="dataDateUnit" label="" width="100" align="center">
        </el-table-column>
        <el-table-column v-for="(month, index) in months" :key="index" :prop="'salesData.' + index" :label="month"
          align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.dataDateUnit == '完成率'">
              {{ scope.row.salesData[index] }}%
            </span>

            <span v-else>
              {{ scope.row.salesData[index] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import * as echarts from "echarts/lib/echarts.js";
import {
  selectSaleTargetList,
  categoryTargetYieldRate,
} from "@/api/productStructure/BiCategoryTargetDwd";
import LineChart from "./components/LineChart";
import barLine from "./components/barLine";

export default {
  dicts: ["sys_sale_category"],
  props: {
    query: {
      type: Object,
      default: () => { },
    },
    dataYear: {
      type: Object,
      default: () => { },
    },
  },
  components: {
    barLine,
    LineChart,
  },
  data() {
    this.chartSettingscompleteRate = {
      // "0.[00]a",
      yAxisType: ["0.[00]", "0.[00]%"],
      showLine: ["达成率"],
      yAxisName: ["数值轴", "比率轴"],
      axisSite: {
        right: ["达成率"],
      },
    };
    this.chartSettingscomplete = {
      // "0.[00]a",
      yAxisType: ["0.[00]", "0.[00]%"],
      showLine: ["完成率"],
      yAxisName: ["数值轴", "比率轴"],
      axisSite: {
        right: ["完成率"],
      },
    };
    this.chartExtend = {
      series(v) {
        v.forEach((i, index) => {
          i.barWidth = 15;
          i.barGap = 0;
          if (i.type !== "line") {
            i.label = {
              show: true,
              position: index === 0 ? 'left' : 'right',
              color: "#333",
              fontSize: 12,
              // formatter: ({ value }) => value.toFixed(2),
              formatter: ({ value }) =>
                value.toLocaleString('en-US', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
            };
          }
        });
        return v;
      },
      xAxis(v) {
        v.forEach((i) => {
          i.show = true;
          i.splitLine = { show: false };
          i.axisTick = { show: true };
          i.axisLine = { show: true };
        });
        return v;
      },
    };
    this.chartExtendcomplete = {
      series(v) {
        v.forEach((i, index) => {
          i.barWidth = 15;
          i.barGap = 0;
          if (i.type !== "line") {
            i.label = {
              show: false,
              position: index === 0 ? 'left' : 'right',
              color: "#333",
              fontSize: 12,
              // formatter: ({ value }) => value.toFixed(2),
              formatter: ({ value }) =>
                value.toLocaleString('en-US', {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2
                })
            };
          }
        });
        return v;
      },
      xAxis(v) {
        v.forEach((i) => {
          i.show = true;
          i.splitLine = { show: false };
          i.axisTick = { show: true };
          i.axisLine = { show: true };
        });
        return v;
      },
    };
    this.yAxis = [
      {
        name: "数值轴",
        show: true,
        splitLine: { show: false }, //去除网格线
        //设置轴线的属性
        axisLabel: {
          color: "#ccc", // 字体
        },
        axisTick: {
          //y轴刻度线
          show: true,
        },
        axisLine: {
          //y轴
          show: true,
        },
      },
      {
        name: "比率轴",
        show: true,
        splitLine: { show: false }, //去除网格线
        //设置轴线的属性
        axisLabel: {
          color: "red",
          formatter: (value) => `${(value * 100).toFixed(0)}%`, // 强制显示百分比
        },
        axisTick: {
          //y轴刻度线
          show: true,
        },
        axisLine: {
          //y轴
          show: true,
        },
      },
    ];
    return {
      productViewList: [],
      productView: "汇总",
      barLineData: {},
      tableData: [], // 用于存储转换后的数据
      months: [], // 用于存储所有月份
      //对比
      barLineChart: {},
      barLineDatatarget: [],
    };
  },
  watch: {
    query: {
      handler: function (newnew, oldold) {
        this.getselectSaleTargetList("salesQuantity");
        this.getcategoryTargetYieldRate();
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.getDicts("sys_sale_category").then((response) => {
      let list = [{ value: "汇总", label: "汇总" }];
      response.data.forEach((item) => {
        list.push({
          value: item.dictValue,
          label: item.dictLabel,
        });
      });
      this.productViewList = list;
    });
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      // return "font-weight: bold;";
      if (row.category === "汇总") {
        return "highlight-row";
      } else {
        return "";
      }
    },
    changeView() {
      this.getselectSaleTargetList("salesQuantity");
    },
    getcategoryTargetYieldRate() {
      categoryTargetYieldRate(this.query).then((response) => {

        this.barLineDatatarget = response;
        this.barLineChart = {
          columns: ["品类", "实际销售额", "销售目标", "达成率"],
          rows: [],
        };

        response.forEach((item) => {
          this.barLineChart.rows.push({
            品类: item.category,
            实际销售额: item.salesAmount,
            销售目标: item.targetAmount,
            达成率: item.completeRate ? item.completeRate / 100 : 0,
          });
        });
      });
    },
    getselectSaleTargetList(property) {
      selectSaleTargetList({ category: this.productView, ...this.query }).then(
        (response) => {

          this.barLineData = {
            columns: ["品类", "实际销售额", "销售目标", "完成率"],
            rows: [],
          };

          response.biCategoryTargetDwdList.forEach((item) => {
            this.barLineData.rows.push({
              品类: item.monthly,
              实际销售额: item.salesAmount,
              销售目标: item.targetAmount,
              完成率: item.completeRate ? item.completeRate / 100 : 0,
            });
          });

          this.tableData = []; // 用于存储转换后的数据
          this.months = []; // 用于存储所有月份
          // 提取所有月份
          response.categorySaleTendData.forEach((item) => {
            for (const month in item.keywordProperty) {
              // const element = array[index];
              if (!this.months.includes(month)) {
                this.months.push(month);
              }
            }
          });
          console.log(JSON.stringify(this.months));

          response.categorySaleTendData.forEach((item) => {
            const row = {
              dataDateUnit: item.dataDateUnit,
              salesData: [],
            };
            this.months.forEach((month) => {
              row.salesData.push(item.keywordProperty[month] || 0);
            });
            this.tableData.push(row);
          });

          return;

          let order = { date: [], data: [] };
          order.date = response.categorySaleStatisticsTend.map(
            (item) => item.dataDateUnit
          );
          response.categorySaleStatisticsTend.forEach((item) => {
            order.data.push(item.keywordProperty);
          });
          const xData = order.date;

          console.log(JSON.stringify(order.data));
          const keyArray = Object.keys(order.data[1]);
          const series = [];
          keyArray.forEach((key) => {
            series.push({
              name: key,
              data: order.data.map((item) => item[key]),
              type: "line",
            });
          });

          const option = {
            grid: {
              left: "5%",
              top: "10%",
              right: "2%",
              bottom: "10%",
            },
            // 提示框
            tooltip: { trigger: "axis" },
            xAxis: {
              data: xData,
            },
            yAxis: {},
            legend: {
              data: keyArray,
            },
            series,
          };

          const E = echarts.init(this.$refs[property]);

          E.setOption(option);
        }
      );
    },
  },
};
</script>
<style lang="scss" >
/* 添加你想要的特定行的CSS样式 */
.highlight-row {
  position: sticky;
  bottom: 0;
  font-weight: bold;
}
</style>
